package cn.ffcs.sort.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataIntegrityViolationException;
import com.opensymphony.xwork2.ActionContext;
import cn.ffcs.base.web.BaseAction;
import cn.ffcs.common.model.Attach;
import cn.ffcs.common.service.AttachService;
import cn.ffcs.common.service.IAttachService;
import cn.ffcs.product.model.Product;
import cn.ffcs.product.model.ProductManager;
import cn.ffcs.product.service.IProductManagerService;
import cn.ffcs.product.service.ProductService;
import cn.ffcs.ref.model.ProductRefSort;
import cn.ffcs.ref.service.IProductRefSortService;
import cn.ffcs.security.model.User;
import cn.ffcs.security.web.UserContext;
import cn.ffcs.sort.model.ProductSort;
import cn.ffcs.sort.service.IProductSortService;
import cn.ffcs.util.MyList;
import cn.ffcs.util.context.ApplicationContextUtil;

/**
 * 产品目录实体类：定义基本属性<br/>
 * <table>
 * <tr>
 * <td>负责人/principal:</td>
 * <td colspan="2">g.huangjx</td>
 * <tr>
 * <td>修改记录/revision:</td>
 * <td colspan="2"></td>
 * </tr>
 * <tr>
 * <td>日期:2009-2-26</td>
 * <td>修改人:g.huanjx</td>
 * <td>修改说明:</td>
 * </tr>
 * <tr>
 * <td></td>
 * <td></td>
 * <td></td>
 * </tr>
 * </table>
 * @author g.huangjx
 * @version $Id$
 */
public class ProductSortAction<D extends ProductSort> extends BaseAction<D>
{
    /** 动态网路标识 */
    private static final long serialVersionUID = -8246991977511117520L;

    /** 产品目录 **/
    private D productSort;
    
    /** 产品目录 **/
    private D parentProductSort; 
    
    /** 产品目录结果集 **/
    private List<D> productSorts;
    
    /** 集团产品目录结果集 **/
    private List<D> teamProdSorts;

    /** 本地产品目录结果集 **/
    private List<D> localProdSorts;

    /** 集团产品目录 **/
    private List teamProdSort;

    /** 本地产品目录 **/
    private List localProdSort;
    
    /** 产品服务 **/
    private ProductService productService;
    
    /** 产品结果集 **/
    private List<Product> products;
    
    /** 附件服务 **/
    private IAttachService attachService;

    /** 产品目录服务 **/
    private IProductRefSortService productRefSortService;

    /** 产品目录服务 **/
    private IProductSortService productSortService;
    
    /** 产品 **/
    private Product product;

    /** 产品目录服务 **/
    private IProductManagerService productManagerService;
    
    private Set prodSet;

    /**
     * 新增或修改产品目录类型数据
     * @return
     */
    public String saveOrUpdate()
    {
        baseService.saveOrUpdate(productSort);
        //lProductSortType=dictTypeService.findAll();  
        returnMsg="保存操作已成功！";
        return SUCCESS;
    }

    /**
     * 删除数据
     * @return
     */
    public String remove()
    {
        baseService.remove(productSort);
        returnMsg = "删除操作已成功！";
        return SUCCESS;
    }
    /**
     * 删除数据
     * @return
     */
    public String deleteSort()
    {
        ActionContext ctx = ActionContext.getContext();        
        HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);   
        HttpServletRequest request =    (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST); 
        response.setCharacterEncoding("gb2312");//页面编码设置
        response.setContentType("text/xml");//页面文件头格式
        try{
            baseService.remove(productSort);
            response.getWriter().write(MyList.getStr("true"));
        }catch(Exception e){
            try{
                response.getWriter().write(MyList.getStr("false"));
            }catch(Exception ee){}
            e.printStackTrace();
            
        }
        return null;
    }
    /**
     * 批量删除
     * @return
     */
    public String batchDel()
    {
//        try{
            String[] ids = getContextObjects("ids");
            baseService.batchDel(ids);
            returnMsg="批量删除操作已成功！";
            return SUCCESS;
//        }catch(DataIntegrityViolationException e){
//            returnMsg="操作失败：数据正在使用中，不能删除！";
//            return "failure";
//        }
    }
    
    /**
     * 
     * 组合查询条件
     * @return
     */
    public Criterion combineCond(){
        Criterion cond = null;
        if (super.getConds() != null)
        {
            //遍历参数表
            Iterator i = super.getConds().entrySet().iterator();
            while (i.hasNext())
            {
                Entry entry = (Entry)i.next();
                String key=(String)entry.getKey();
                if (super.getConds().get(key) != null
                        && !StringUtils.isEmpty(super.getConds().get(key).toString()))
                {
                    //根据实际情况做处理
                    Criterion temp=null;
                    if (key.equalsIgnoreCase("name")){
                        temp=Restrictions.like(key, "%"+super.getConds().get(key).toString()+"%");
                    }else if (key.equalsIgnoreCase("conds.sortType")){
                        temp=Restrictions.eq(key, Integer.parseInt(super.getConds().get(key).toString()));
                    }else{
                        temp=Restrictions.eq(key, super.getConds().get(key));                        
                    }
                    
                    if (cond == null)
                    {
                        cond = temp;
                    }
                    else
                    {
                        cond = Restrictions.and(cond, temp);
                    }
                }
            }
        }
        return cond;
    }

    /**
     * 根据关键值获取实体数据
     * @return
     */
    public String findById()
    {
        if (productSort != null &&productSort.getId()!=null&& productSort.getId() != 0)
        {
            productSort = (D) baseService.findById(productSort.getId());
        }
        //lProductSortType=dictTypeService.findAll();        
        
        return SUCCESS;
    }
    /**
     * 产品类型树
     * @return
     */
    public String findTree(){
        ActionContext ctx = ActionContext.getContext();        
        HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);   
        HttpServletRequest request =    (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST); 
        String type=request.getParameter("type");
        String module=request.getParameter("module");
        List ls=super.findBy();
        String xml=MyList.getProductSortTree(ls,type,module);
        response.setCharacterEncoding("gb2312");//页面编码设置
        response.setContentType("text/xml");//页面文件头格式
        try{
        response.getWriter().write(xml);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 产品类型视图
     * @return
     */
    public String findView(){
        ActionContext ctx = ActionContext.getContext();        
        HttpServletRequest request =    (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST); 
        String type=request.getParameter("type");
        type=StringUtils.defaultIfEmpty(type, "1");
        User currUser = ApplicationContextUtil.getUserContextObject()
        .getCurrUser();
        String sortType=request.getParameter("conds.sortType");
        String sortId=request.getParameter("conds.parentSort");
        if (type.equalsIgnoreCase("1")){
            if("1".equals(sortType)){
                teamProdSorts=super.findByAndOrder("begin", "ASC");
                productSorts=teamProdSorts;
            }else{
                localProdSorts=super.findByAndOrder("begin", "ASC");
                productSorts=localProdSorts;
            }
        }else{
            if("1".equals(sortType)){
                teamProdSorts=super.findByAndOrder("begin", "DESC");
                productSorts=teamProdSorts;
            }else{
                localProdSorts=super.findByAndOrder("begin", "DESC");
                productSorts=localProdSorts;
            }
        }
        if (productSort != null && productSort.getId() != 0)
        {
            productSort = (D) baseService.findById(productSort.getId());
        }
        
        //查询出当前人负责的所有产品
        if(currUser!=null&&currUser.getPerson()!=null){
            Criterion cond1 = Restrictions.eq("person", currUser.getPerson());
            List<ProductManager> prodManagers=productManagerService.findBy(cond1);
            prodSet=listToSet(prodManagers);
        }
        
        products=productService.findBySort(sortId);
        if(request.getParameter("singleupdate")!=null){
            if(sortId!=null&&!sortId.equals("")&&!sortId.equals("0")){
                parentProductSort=baseService.findById(new Integer(sortId));//父目录
            }else{//父目录是根目录
                parentProductSort=(D)new ProductSort();
                parentProductSort.setId(0);
                parentProductSort.setSortType(sortType);
                if(sortType.equals("1")){
                    parentProductSort.setName("集团产品目录");
                }else{
                    parentProductSort.setName("福建省产品目录");
                }
            }
            return request.getParameter("singleupdate");
        }
        return SUCCESS;
    }
    
    public Set listToSet(List<ProductManager> list){
        Set set=new HashSet();
        if(list==null){
            return set;
        }
        ProductManager pm;
        for(int i=0;i<list.size();i++){
            pm=list.get(i);
            set.add(pm.getProduct().getId());
        }
        return set;
    }
    
    public String findNewProduct()
    {
        ////获得新的产品信息
        Criterion cond=null;
        cond=Restrictions.eq("isNew", "1");   
        products=productService.findBy(cond);
        for(Product prod : products){
            if (prod != null)
            {
                Criterion cond1 = Restrictions.eq("fileType", "pic");
                Criterion cond2 = Restrictions.eq("refEntityID", prod.getId().toString());
                Criterion condAttach = Restrictions.and(cond1, cond2);
                List<Attach> attachs = attachService.findBy(condAttach);
                if(attachs!=null&&attachs.size()>1){
                    List<Attach> list=new ArrayList();
                    list.add(attachs.get(0));
                    prod.setAttachs(list);
                }
            }
        }
        return SUCCESS;
    }
    
    public String findLocalView(){
        return findView();
    }
    /**
     * 导出EXCEL
     * @return
     */
    public String findExcel(){
        productSorts= super.findByAndOrder("begin", "ASC");
        return SUCCESS;
    }
    /**
     * 产品类型视图
     * @return
     */
    public String findNextView(){
        ActionContext ctx = ActionContext.getContext();        
        HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);   
        productSorts=super.findByAndOrder("begin", "ASC");
        String xml=MyList.getAll(productSorts);
//        System.out.println(xml);
        response.setCharacterEncoding("gb2312");//页面编码设置
        response.setContentType("text/xml");//页面文件头格式
        try{
            response.getWriter().write(xml);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 获取产品目录进行展示
     * @return
     */
    public String showProductSortById()
    {
        ActionContext ctx = ActionContext.getContext();        
        HttpServletRequest request = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);   
        String id=request.getParameter("product.id");
        if (id != null && id != "")
        {
            Criterion cond=null;
            boolean team=false;
            boolean local=false;
            List<ProductRefSort> productRefSort=null;
            cond = Restrictions.eq("product", id);
            productRefSort=productRefSortService.findBy(cond);
            if(teamProdSort==null){
                teamProdSort=new ArrayList();
            }
            if(localProdSort==null){
                localProdSort=new ArrayList();
            }
            for(int j=0;j<productRefSort.size();j++){
                List productSort=productSortService.findProductSortById(productRefSort.get(j).getSort());
                if(productSort!=null&&productSort.size()>0){
                    ProductSort pSort=(ProductSort)productSortService.findById(new Integer(productSort.get(productSort.size()-1).toString()));
                    if("1".equals(pSort.getSortType())){
                        team=true;
                        teamProdSort.add(productSort);
                    }
                    else if("2".equals(pSort.getSortType())){
                        local=true;
                        localProdSort.add(productSort);
                    }
                }
            }
            if(this.getConds()==null)
                this.setConds(new HashMap<String, Object> ());
            this.getConds().put("parentSort", "0");
            if(local){
                this.getConds().put("sortType", "2");
                localProdSorts=this.findByAndOrder("begin", "ASC");
            }
            else if(team){
                this.getConds().put("sortType", "1");
                teamProdSorts=this.findByAndOrder("begin", "ASC");
            }
        }
        return SUCCESS;
    }   
    
    
    
    /**
     * 获取产品目录类型
     * @return
     */
    public D getProductSort()
    {
        return productSort;
    }

    /**
     * 设置产品目录类型
     * @param dict
     */
    public void setProductSort(D productSort)
    {
        this.productSort = productSort;
    }

    /**
     * 获取结果集
     * @return
     */
    public List<D> getProductSorts()
    {
        return productSorts;
    }

    /**
     * 设置结果集
     * @param dicts
     */
    public void setProductSorts(List<D> productSorts)
    {
        this.productSorts = productSorts;
    }

    public IAttachService getAttachService()
    {
        return attachService;
    }

    public void setAttachService(IAttachService attachService)
    {
        this.attachService = attachService;
    }

    public List<D> getLocalProdSorts()
    {
        return localProdSorts;
    }

    public void setLocalProdSorts(List<D> localProdSorts)
    {
        this.localProdSorts = localProdSorts;
    }

    public List<D> getTeamProdSorts()
    {
        return teamProdSorts;
    }

    public void setTeamProdSorts(List<D> teamProdSorts)
    {
        this.teamProdSorts = teamProdSorts;
    }

    public IProductRefSortService getProductRefSortService()
    {
        return productRefSortService;
    }

    public void setProductRefSortService(
            IProductRefSortService productRefSortService)
    {
        this.productRefSortService = productRefSortService;
    }

    public IProductSortService getProductSortService()
    {
        return productSortService;
    }

    public void setProductSortService(IProductSortService productSortService)
    {
        this.productSortService = productSortService;
    }

    public Product getProduct()
    {
        return product;
    }

    public void setProduct(Product product)
    {
        this.product = product;
    }

    public List getLocalProdSort()
    {
        return localProdSort;
    }

    public void setLocalProdSort(List localProdSort)
    {
        this.localProdSort = localProdSort;
    }

    public List getTeamProdSort()
    {
        return teamProdSort;
    }

    public void setTeamProdSort(List teamProdSort)
    {
        this.teamProdSort = teamProdSort;
    }

    public D getParentProductSort()
    {
        return parentProductSort;
    }

    public void setParentProductSort(D parentProductSort)
    {
        this.parentProductSort = parentProductSort;
    }

    public List<Product> getProducts()
    {
        return products;
    }

    public void setProducts(List<Product> products)
    {
        this.products = products;
    }

    public ProductService getProductService()
    {
        return productService;
    }

    public void setProductService(ProductService productService)
    {
        this.productService = productService;
    }

    public Set getProdSet()
    {
        return prodSet;
    }

    public void setProdSet(Set prodSet)
    {
        this.prodSet = prodSet;
    }

    public IProductManagerService getProductManagerService()
    {
        return productManagerService;
    }

    public void setProductManagerService(
            IProductManagerService productManagerService)
    {
        this.productManagerService = productManagerService;
    }
    

}
